package com.github.rxyor.common.support.util;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;

/**
 *<p>
 *
 *</p>
 *
 * @author liuyang
 * @date 2019/12/31 周二 00:35:00
 * @since 1.0.0
 */
public class RedisKeyBuilder implements InitializingBean {

    private static RedisKeyBuilder instance;

    @Value("${spring.application.name}")
    private final String appName;

    @Value("${redis.splitter:::}")
    private final String splitter;

    public RedisKeyBuilder(@Value("${spring.application.name}") String appName,
        @Value("${redis.splitter:::}") String splitter) {
        this.splitter = StringUtils.isBlank(splitter) ? "::" : splitter;
        this.appName = appName;
    }

    public static String append(String key) {
        if (StringUtils.isBlank(key)) {
            return key;
        }
        if (instance == null) {
            instance = new RedisKeyBuilder(null, "::");
        }
        if (StringUtils.isNotBlank(instance.appName)) {
            return instance.appName + instance.splitter + key;
        }
        return key;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        RedisKeyBuilder.instance = this;
    }
}
